package com.elitesland.core.config.argument.resolver;

import com.alibaba.excel.EasyExcel;
import com.elitesland.core.config.argument.ImportExcel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.IOException;
import java.io.InputStream;

/**
 * 解析上传的excel数据.
 *
 * @author Kaiser（wang shao）
 * @date 2020-12-30
 */
public class ImportExcelMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private final Logger logger = LoggerFactory.getLogger(ImportExcelMethodArgumentResolver.class);

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(ImportExcel.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        ImportExcel importExcel = parameter.getParameterAnnotation(ImportExcel.class);
        if (importExcel == null) {
            return null;
        }

        MultipartHttpServletRequest request = webRequest.getNativeRequest(MultipartHttpServletRequest.class);
        if (request == null) {
            logger.info("获取上传文件失败，非MultipartRequest！");
            return null;
        }
        long start = System.currentTimeMillis();
        var data = obtainData(request, importExcel);
        logger.info("解析上传数据完毕，用时：{}", System.currentTimeMillis() - start);
        return data;
    }

    private Object obtainData(MultipartHttpServletRequest request, ImportExcel importExcel) {
        MultipartFile file = request.getFile(importExcel.fileName());
        if (file == null) {
            return null;
        }

        ExcelDataListener excelDataListener = new ExcelDataListener();
        excelDataListener.getExcelImportVO().get().setTableName(file.getName());
        try (InputStream inputStream = file.getInputStream()) {
            EasyExcel.read(inputStream, excelDataListener).sheet(0).headRowNumber(importExcel.headerRow()).doRead();
        } catch (IOException e) {
            logger.error("解析导入的文件失败", e);
            return null;
        }

        return excelDataListener.getExcelImportVO().get().getDataMapsList();
    }
}
